package bbdd;


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by juanky on 4/12/14.
 */
public class Conexion {

    private Connection cnx;
    private DataSource ds;
    private Context context;
    private InitialContext contextInitial;

    public Conexion() {
        try {
            contextInitial = new InitialContext();
            context = (Context) contextInitial.lookup("java:comp/env");
            ds = (DataSource) context.lookup("jdbc/MotoGPLeague");
            cnx = ds.getConnection();
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Conexion cnx, PreparedStatement ps, ResultSet rs) {
        try {
            rs.close();
            ps.close();
            cnx.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public PreparedStatement getConexion(String sql, String[] strings) throws SQLException {
        return cnx.prepareStatement(sql, strings);
    }

    private void close() throws SQLException {
        cnx.close();
    }

    public PreparedStatement getConexion(String sql) throws SQLException {
        return cnx.prepareStatement(sql);
    }
}
